package top.yeyusmile.service;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.sun.management.OperatingSystemMXBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.yeyusmile.common.MsgType;
import top.yeyusmile.common.MyTemplate;
import top.yeyusmile.common.RobotConfig;
import top.yeyusmile.mirai.AddReq;
import top.yeyusmile.mirai.Sender;
import top.yeyusmile.mirai.msg.ImageMsg;
import top.yeyusmile.mirai.msg.PlainMsg;
import top.yeyusmile.utils.MyQQUtil;

import java.io.UnsupportedEncodingException;
import java.lang.management.ManagementFactory;
import java.util.*;

/**
 * 接收信息处理中心
 *
 * @author 夜雨
 * @Web www.yeyusmile.top
 * @date 2022/4/14 14:17
 */
@Slf4j
@Service
public class DealMsgService {

    @Autowired
    private RobotConfig robotConfig;

    @Autowired
    private BlackWordService blackWordService;

    //聊天功能
    //private Map<Long, Boolean> chatGroups = new HashMap<>();


    //存旧的信息，方便撤回
    private List<JsonObject> saveMsg = new LinkedList<>();//每一条数数据

    private static final int CAPACITY = 2000;//存2000条 防撤回用

    private Gson gson = MyQQUtil.getGson();

    @Autowired
    private MyTemplate myTemplate;

    @Autowired
    private DianGeService dianGeService;
    //
//    @Autowired
//    private SendMsgService sendMsgService;
//
    @Autowired
    private ConvenientService convenientService;

    @Autowired
    private QbangService qbangService;
//
//    @Autowired
//    private BlackWordService blackWordService;
//
//    @Autowired
//    private OtherService otherService;


    /**
     * @param raw 源数据
     * @throws Exception
     */
    public void dealMsg(String raw) throws Exception {

        JsonObject root = MyQQUtil.getRoot(raw);
        int code = root.get("code").getAsInt();
        if (code != 0) {
            log.info(root.toString());
            return;
        }
        JsonArray data = root.get("data").getAsJsonArray();

        for (int i = 0; i < data.size(); i++) {
            JsonObject obj = data.get(i).getAsJsonObject();
            String msgChainType = obj.get("type").getAsString();//接收类型
            Sender sender = null;
            try {
                JsonObject senderjson = obj.get("sender").getAsJsonObject();
                sender = gson.fromJson(senderjson, Sender.class);
            } catch (Exception e) {
                //System.out.println(obj);
            }

            if (msgChainType.contains(MsgType.MSGTYPE_GROUP)) {//群消息
                dealGroupMsg(sender, obj);

            }

            if (msgChainType.contains(MsgType.MSGTYPE_FRIEDN)) {//好友消息
                dealFrindMsg(sender, obj);

            }


            if (msgChainType.contains(MsgType.MSGTYPE_MemberCardChangeEvent)) {//群名片改动
                Sender member = null;
                try {
                    JsonObject memberjson = obj.get("member").getAsJsonObject();
                    member = gson.fromJson(memberjson, Sender.class);
                } catch (Exception e) {
                    //System.out.println(obj);
                }
                MemberCardChangeEvent(member, obj);

            }

            if (msgChainType.contains(MsgType.MSGTYPE_MemberLeaveEventKick)) {//某人被T
                Sender member = null;
                try {
                    JsonObject memberjson = obj.get("member").getAsJsonObject();
                    member = gson.fromJson(memberjson, Sender.class);
                } catch (Exception e) {
                    //System.out.println(obj);
                }
                MemberLeaveEventKick(member, obj);

            }
            if (msgChainType.contains(MsgType.MSGTYPE_MemberLeaveEventQuit)) {//某人退群
                Sender member = null;
                try {
                    JsonObject memberjson = obj.get("member").getAsJsonObject();
                    member = gson.fromJson(memberjson, Sender.class);
                } catch (Exception e) {
                    //System.out.println(obj);
                }
                MemberLeaveEventQuit(member, obj);

            }

            if (msgChainType.contains(MsgType.MSGTYPE_NewFriendRequestEvent)) {//好友申请
                NewFriendRequestEvent(obj);

            }

            if (msgChainType.contains(MsgType.MSGTYPE_BotInvitedJoinGroupRequestEvent)) {//被群邀请申请
                BotInvitedJoinGroupRequestEvent(obj);

            }

            if (msgChainType.contains(MsgType.MSGTYPE_GroupRecallEvent)) {//群撤回解析
                GroupRecallEvent(obj);

            }


        }

    }

    /**
     * 群撤回事件解析
     *
     * @param obj
     */
    private void GroupRecallEvent(JsonObject obj) {
        if (!robotConfig.getGoBackcSwitch()) return;

        Sender operator = null;
        try {
            JsonObject operatorJson = obj.get("operator").getAsJsonObject();
            operator = gson.fromJson(operatorJson, Sender.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int messageId = obj.get("messageId").getAsInt();

        for (JsonObject sMsg : saveMsg) {//防撤回
            List<Object> params = new ArrayList<>();
            params.add(new PlainMsg(operator.getMemberName() + "撤回了：\n"));
            boolean f = false;
            JsonArray messagesChains = sMsg.get("messageChain").getAsJsonArray();
            for (int i = 0; i < messagesChains.size(); i++) {
                JsonObject msgObj = messagesChains.get(i).getAsJsonObject();
                String msgType = msgObj.get("type").getAsString();//消息类型
                if (msgType.contains(MsgType.MSGTYPE_SOURCE)) {
                    int msgId = msgObj.get("id").getAsInt();
                    if (messageId != msgId) {
                        break;
                    } else {
                        f = true;
                    }
                } else {
                    params.add(msgObj);
                }
            }
            if (f) {//找到发送
                if (new Gson().toJson(params).indexOf("Q群管家") != -1) {
                    break;//取消撤回
                }
                myTemplate.sendMsg2Group(params, null, operator.getGroup().getId());
                break;
            }
        }
    }


    /**
     * 被邀请入群
     *
     * @param obj
     */
    private void BotInvitedJoinGroupRequestEvent(JsonObject obj) {
        AddReq beInvitedGroupReq = gson.fromJson(obj, AddReq.class);
        beInvitedGroupReq.setOperate(0);//同意
        beInvitedGroupReq.setSessionKey(robotConfig.getSessionKey());
        myTemplate.opBeinviteGrop(beInvitedGroupReq);
    }

    /**
     * 好友申请同意
     *
     * @param obj
     */
    private void NewFriendRequestEvent(JsonObject obj) {
        AddReq addFriendReq = gson.fromJson(obj, AddReq.class);
        addFriendReq.setOperate(0);//同意
        addFriendReq.setSessionKey(robotConfig.getSessionKey());
        myTemplate.opNewFried(addFriendReq);

    }

    private void MemberLeaveEventQuit(Sender member, JsonObject obj) {
        log.info(member.getId() + "离开群聊");
        List<Object> params = new ArrayList<>();
        params.add(new PlainMsg(member.getId() + "已经离开群聊"));
        //myTemplate.sendMsg2Group(params, null, member.getGroup().getId());
    }

    private void MemberLeaveEventKick(Sender member, JsonObject obj) {
        log.info(member.getId() + "被T出群聊");
        List<Object> params = new ArrayList<>();
        params.add(new PlainMsg(member.getId() + "已经被T出群聊"));
        //myTemplate.sendMsg2Group(params, null, member.getGroup().getId());
    }

    private void MemberCardChangeEvent(Sender member, JsonObject obj) {

        String origin = obj.get("origin").getAsString();
        String current = obj.get("current").getAsString();
        log.info("将群名片修改为：" + current);
        List<Object> params = new ArrayList<>();
        params.add(new PlainMsg(origin + "将群名片修改为：" + current));
        // myTemplate.sendMsg2Group(params, null, member.getGroup().getId());

    }


    /**
     * obj:
     * {
     * "type": "GroupMessage",
     * "messageChain": [
     * {
     * "type": "Source",
     * "id": 9010,
     * "time": 1649928060
     * },
     * {
     * "type": "Image",
     * "imageId": "{7943931D-C508-2485-2C2A-BAF7687154B8}.jpg",
     * "url": "http://gchat.qpic.cn/gchatpic_new/1545417642/750406452-2249698507-7943931DC50824852C2ABAF7687154B8/0?term=2",
     * "path": null,
     * "base64": null
     * }
     * ],
     * "sender": {
     * }
     * },
     *
     * @param sender
     * @param obj
     */
    private void dealGroupMsg(Sender sender, JsonObject obj) throws UnsupportedEncodingException {

        if (saveMsg.size() < CAPACITY) {
            saveMsg.add(obj);
        } else {
            saveMsg.remove(0);
            saveMsg.add(obj);
        }

        JsonArray messagesChains = obj.get("messageChain").getAsJsonArray();
        for (int i = 0; i < messagesChains.size(); i++) {
            JsonObject msgObj = messagesChains.get(i).getAsJsonObject();
            String msgType = msgObj.get("type").getAsString();//消息类型
            if (msgType.contains(MsgType.MSGTYPE_PLAIN)) {//解析文本数据
                String msg = msgObj.get("text").getAsString();
                if ("菜单".equals(msg) || "功能".equals(msg)) {
                    List<Object> params = new ArrayList<>();
                    params.add(new PlainMsg(getMenu()));
                    myTemplate.sendMsg2Group(params, null, sender.getGroup().getId());
                    break;
                }

                if ("博客".equals(msg)) {
                    List<Object> params = new ArrayList<>();
                    params.add(new PlainMsg("https://yeyusmile.top/"));
                    myTemplate.sendMsg2Group(params, null, sender.getGroup().getId());
                    break;
                }


                if ("加入交流群".equals(msg)) {
                    List<Object> params = new ArrayList<>();
                    params.add(new PlainMsg("873388675"));
                    myTemplate.sendMsg2Group(params, null, sender.getGroup().getId());
                    break;
                }

                if (msg != null && !"".equals(msg)) {
                    //处理事件
                    if (msg.contains("查询")) {
                        if (msg.matches("查询[1-9][0-9]{3,9}")) {
                            qbangService.query(msg.replaceAll("查询", ""), sender, 0);
                        }
                        break;
                    }

                    if (msg.contains("绑查Q")) {
                        qbangService.query(msg.replaceAll("绑查Q", ""), sender, 1);
                        break;
                    }
                    if (msg.contains("查微博")) {
                        qbangService.query(msg.replaceAll("查微博", ""), sender, 3);
                        break;
                    }
                    if (msg.contains("绑查微博")) {
                        qbangService.query(msg.replaceAll("绑查微博", ""), sender, 4);
                        break;
                    }

                    if (msg.contains("LOL查Q")) {
                        qbangService.query(msg.replaceAll("LOL查Q", ""), sender, 2);
                        break;
                    }

                    if (msg.equals("随机语录")) {
                        convenientService.quotation(sender);
                        break;
                    }

                    if (msg.equals("舔狗日记")) {
                        convenientService.diary(sender);
                        break;
                    }

                    if (msg.equals("笑话")) {
                        convenientService.joke(sender);
                        break;
                    }

                    if (msg.equals("段子")) {
                        convenientService.duanzi(sender);
                        break;
                    }
                    if (msg.equals("绕口令")) {
                        convenientService.raokouling(sender);
                        break;
                    }

                    if (msg.contains("QQ凶吉")) {
                        convenientService.qqLucky(msg.replaceAll("QQ凶吉", ""), sender);
                        break;
                    }

                    if (msg.equals("看美女") || "美女".equals(msg) || msg.contains("看")) {
                        convenientService.lookGirl(sender, msg.replaceAll("看", ""));
                        break;
                    }

                    if (msg.contains("动漫") || "二次元".equals(msg)) {
                        convenientService.lookAnime(sender);
                        break;
                    }

                    if (msg.contains("禁言") && msg.length() > 5) {
                        if (sender.toString().toLowerCase(Locale.ROOT).indexOf("owner") != -1
                                || sender.toString().toLowerCase(Locale.ROOT).indexOf("admin") != -1) {

                            myTemplate.mute(600, Long.parseLong(msg.replaceAll("禁言", "")),
                                    sender.getGroup().getId(), 1);
                        }
                        break;
                    }
                    if (msg.contains("解禁") && msg.length() > 5) {
                        if (sender.toString().toLowerCase(Locale.ROOT).indexOf("owner") != -1
                                || sender.toString().toLowerCase(Locale.ROOT).indexOf("admin") != -1) {

                            myTemplate.mute(null, Long.parseLong(msg.replaceAll("禁言", "")),
                                    sender.getGroup().getId(), 0);
                        }
                        break;
                    }

//                    if ("插件开源".equals(msg)) {
//                        List<Object> params = new ArrayList<>();
//                        params.add(new PlainMsg("https://gitee.com/yang10560/MiraiYeYuRobot"));
//                        myTemplate.sendMsg2Group(params, null, sender.getGroup().getId());
//
//                        break;
//                    }


                    if (msg.contains("点歌")) {
                        dianGeService.diange(sender, msg);
                        break;
                    }

                    //网易
                    if (msg.contains("网易")) {
                        dianGeService.netEase(sender, msg);
                        break;
                    }

                    if (msg.equals("状态")) {
                        List<Object> params = new ArrayList<>();
                        params.add(new PlainMsg(getStatus()));
                        myTemplate.sendMsg2Group(params, null, sender.getGroup().getId());
                        break;
                    }


                    //聊天
//                    if (msg.equals("开启助手")) {
//                        chatGroups.put(sender.getGroup().getId(), true);
//                        break;
//                    }
//
//                    if (msg.equals("关闭助手")) {
//                        chatGroups.put(sender.getGroup().getId(), false);
//                        break;
//                    }

//                    if (chatGroups.get(sender.getGroup().getId()) != null &&
//                            chatGroups.get(sender.getGroup().getId())) {
                    if ((msg.contains("小明") || msg.contains("你")
                            || msg.contains("我") || msg.contains("他")
                            || msg.contains("在") || msg.contains("好")
                            || msg.contains("嗯") || msg.contains("晚安")
                            || msg.contains("早") || msg.contains("哈哈")
                            || msg.contains("踢") || msg.contains("什么")
                    ) && msg.length() < 50) {
                        convenientService.chat(sender, msg.replaceAll("小明", ""));
                        break;
                    }

                    //违禁词交给机器人处理
                    if (blackWordService.isBlackWord(msg) && msg.length() < 50) {
                        convenientService.chat(sender, msg);
                        break;
                    }

                    // }


                }


            }


            if (msgType.contains(MsgType.MSGTYPE_FLASHIMAGE)) {//闪照破解

                if (!robotConfig.getFlashPicSwitch()) return;

                List<Object> params = new ArrayList<>();
                ImageMsg flashMsg = gson.fromJson(msgObj, ImageMsg.class);
                flashMsg.setType(MsgType.MSGTYPE_IMAGE);
                params.add(flashMsg);
                myTemplate.sendMsg2Group(params, null, sender.getGroup().getId());
                break;
            }

        }
    }


    /**
     * @param sender
     * @param obj
     */
    private void dealFrindMsg(Sender sender, JsonObject obj) {
        List<Object> params = new ArrayList<>();
        params.add(new PlainMsg("不再处理好友消息。只处理群信息"));
        // myTemplate.sendMsg2Friend(params, null, sender.getId());
    }


    private String getStatus() {

        StringBuilder sb = new StringBuilder();
        OperatingSystemMXBean mem = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        sb.append("Total RAM：").append(mem.getTotalPhysicalMemorySize() / 1024 / 1024).append("MB\n");
        sb.append("Available　RAM：").append(mem.getFreePhysicalMemorySize() / 1024 / 1024).append("MB\n");
        Properties props = System.getProperties();
        sb.append("Java的运行环境版本：").append(props.getProperty("java.version")).append("\n");
        sb.append("操作系统的名称：").append(props.getProperty("os.name")).append("\n");
        sb.append("操作系统的构架：").append(props.getProperty("os.arch")).append("\n");
        sb.append("操作系统的版本：").append(props.getProperty("os.version")).append("\n");
        return sb.toString();

    }


    //测试用
    //if (3 > 2) return new ReqResult(200);
    //if (message.getMqType() != 2006 || message.getMqType() != 2007)
    // return new ReqResult(100);

    // message.setMqMsg(URLDecoder.decode(message.getMqMsg(), "utf-8"));
    //String msg = message.getMqMsg();

    // if (blackWordService.isBlackWord(raw) return new ReqResult(-1);

/*
        switch (message.getMqType()) {
            case TypeConstant.MSGTYPE_NODEFINE://消息类型_未定义
                break;
            case TypeConstant.MSGTYPE_FRIEDN://消息类型_好友
            case TypeConstant.MSGTYPE_GROUP://消息类型_群





                if (message != null && msg != null) {

                    if (msg.contains("ip探针") && msg.length() < 20) {
                        otherService.ip(message);
                        break;
                    }






                    if (msg.contains("天气") && msg.length() < 10) {
                        convenientService.weather(msg.replaceAll("天气", ""), message);
                        break;
                    }



                }
                break;
            case TypeConstant.MSGTYPE_GROUP_RECALL_MSG://消息类型_群撤回
            case TypeConstant.MSGTYPE_FREND_RECALL_MSG://消息类型_好友撤回
                System.out.println(message);
                if (!robotConfig.getGoBackcSwitch()) return new ReqResult(-1);
                for (MyQQMessage sMsg : saveMsg) {
                    if (sMsg.getMqMsgseq().equals(message.getMqMsgseq()) &&
                            sMsg.getMqMsgid().equals(message.getMqMsgid())
                            && !message.getMqFromqq().equals(robotConfig.getRobotQQ())) {
                        sendMsgService.sendMsg("[@" + message.getMqFromqq() + "] 撤回:" + sMsg.getMqMsg(), sMsg);
                        break;
                    }
                }//防撤回
                break;

            case TypeConstant.MSGTYPE_BE_INVITE_TO_GROUP:
                System.out.println("某人申请加群：" + message);
                if (robotConfig.containGid(message.getMqFromid())) {
                    sendMsgService.handleGroupInvite(TypeConstant.DEAL_AGREE_CONFIRM, message);
                }//同意加群
                break;

            case TypeConstant.MSGTYPE_BE_ADD_FRIEND:
                System.out.println("被申请好友：" + message);
                if (robotConfig.getAddFrendSwitch()) {
                    sendMsgService.handleFriendEvent(TypeConstant.DEAL_AGREE_CONFIRM, message);
                }//同意好友
                break;
            case TypeConstant.MSGTYPE_ME_BE_INVITE_GROUP:
                System.out.println("我被邀请进群" + message.getMqFromqq());
                if (robotConfig.getAddGroupSwitch()) {
                    sendMsgService.handleGroupInvite(TypeConstant.DEAL_AGREE_CONFIRM, message);
                }

                break;
            case TypeConstant.MSGTYPE_GROUP_FILE_RECEIVE:

                log.info("群文件接收,{}", message);

                otherService.alertGroupFileReceive(message);

                break;


        }
*/


    //   }


    private String getMenu() {
        /*return "------菜单-功能------\n" +
                "[点歌+歌名或歌手]  说明(如：点歌周杰伦稻香)\n" +
                // "[60s] 说明(60秒读懂世界，每天7点播报)\n" +
                "[随机语录]  [舔狗日记] \n" +//[历史上的今天]
                "[看美女] [看xx] [二次元] [绕口令]  \n" +
                "[某地 + 天气] [QQ凶吉 + ＱＱ号]" +
                "[查询 + ＱＱ号] [绑查Q + 手机号] [查微博 + 微博ID]\n" +
                "[绑查微博 + 手机号] [LOL查Q + 昵称]\n" +
                "[加入交流群] [博客] [插件开源] [ip探针+伪装标题]\n" +
                "---------------------\n" +
                "默认开启功能：\n" +
                "群闪照破解;群消息防撤;自动同意好友;自动同意加群\n" +
                "群申请自动同意;违禁词检测;退群,名片更改提醒\n" +
                "------夜雨小屋------\n"+
                "-----power by mirai-----";*/

        return "------菜单-功能------\n" +
                "[小明+你要说要的话](如：小明北京天天气)\n" +
                "[点歌+歌名或歌手](如：点歌周杰伦稻香)\n" +
                "[网易+歌手歌名] (使用网易搜索)\n" +
                "[随机语录]  [舔狗日记] \n" +//[历史上的今天]
                "[看美女] [看XX] [二次元] [绕口令]  \n" +
                "[QQ凶吉+Ｑ号] [禁言/解禁+Ｑ号]" +
                "[查询+Ｑ号] [加入交流群] [状态]\n" +//[绑查Q+手机] [查微博+微博ID]
                // "[绑查微博+手机号] [LOL查Q+昵称]\n" +
                // "\n " + //[ip探针+伪装标题]\n" +
                "------拉我入群即可-------\n" +
                "群消息防撤;群闪照破解;自动同意好友和群\n" +
                "------夜雨小屋------\n" +
                "-----Power By Mirai Robot-----";

    }

}
